package com.lianyu507.service.impl;


import com.lianyu507.bean.LoginResult;
import com.lianyu507.pojo.MbUser;
import com.lianyu507.pojo.MbUserExample;
import com.lianyu507.service.LoginService;
import com.lianyu507.service.MbUserService;
import com.lianyu507.util.ExceptionUtil;
import com.lianyu507.util.MD5;
import com.lianyu507.util.UserContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;
import java.util.UUID;

@Service
public class LoginServiceImpl implements LoginService {

    @Autowired
    private MbUserService mbUserMapper;
    @Override
    public LoginResult login(String userName, String password) {
        MbUserExample example = new MbUserExample();
        MbUserExample.Criteria criteria = example.createCriteria();
        criteria.andUserNameEqualTo(userName);
        List<MbUser> list = mbUserMapper.selectByExample(example);
        if (list != null && list.get(0).getStatus() == 1) {
            if (!list.get(0).getUserPassword().equals(MD5.encode(password))) {
                throw new RuntimeException("密码错误");
            }
            MbUser user=list.get(0);
            LoginResult result=new LoginResult();
            result.setId(user.getId());
            result.setName(userName);
            result.setToken(UUID.randomUUID().toString());
            user.setToken(result.getToken());
            //把用户信息写入session
            UserContext.putCurrentUser(user);
            return result;

        } else {
            throw new RuntimeException("用户不存在");
        }
    }

    @Override
    public MbUser getSession() {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        HttpSession session = request.getSession();

        String username = (String) session.getAttribute("userName");

        if (username == null || org.apache.commons.lang3.StringUtils.isBlank(username)) {
            return null;
        }

        MbUserExample example = new MbUserExample();
        MbUserExample.Criteria criteria = example.createCriteria();
        criteria.andUserNameEqualTo(username);
        List<MbUser> list = null;
        try {
            list = mbUserMapper.selectByExample(example);
            if (list.get(0) == null || list.size() == 0) {
                return null;
            }
        } catch (Exception e) {

            System.err.println(ExceptionUtil.getStackTrace(e));
            return null;
        }
        MbUser user = (MbUser) list.get(0);
        return user;
    }

}
